<!--
 * @Description: 群组和添加好友列表
 * @Author: Kerwin
 * @Date: 2025-04-12 16:06:16
 * @LastEditTime: 2025-04-17 15:11:25
 * @LastEditors:  Please set LastEditors
-->

<template>
  <view class="content">
    <!-- <view class="group">
            <view class="group-item" v-for="(item, index) in groupList" :key="index">
                <view class="group-item-left">
                </view>
                <view class="group-item-right">
                    {{ item.name }}
                </view>
            </view>
        </view> -->
    <view class="title">
      {{ listType.type == 'friend' ? '好友申请' : '已加入的群组' }}
    </view>
    <view class="group" v-if="listType.type != 'friend'">
      <view class="group-item" @click="toChat(item)" v-for="(item, index) in groupList">
        <u-avatar :src="getImgFullPath(item.avatar)" mode="square"></u-avatar>
        <view class="titleGicon"> {{ item.name }}</view>
      </view>
      <u-empty v-if="groupList.length <= 0" text="暂无群组，快去加入群组吧~" mode="list"></u-empty>

    </view>
    <view class="group" v-else>
      <view class="group-item" v-for="(item, index) in friendList">
        <u-avatar :src="getImgFullPath(item.userDetail.avatar)" mode="square"></u-avatar>
        <view class="titleGicon">
          <view>
            <view class="word1"> {{ item.userDetail.name }}</view>
            <view class="word2"> {{ item.msg }}</view>
          </view>
          <view style="width: 40%;background-color: pink;">
            <!-- <u-button style="width: 100%;" size="mini" type="success">查看</u-button> -->
            <van-button @click="handleAddFriend(item)" style="width: 100%;" size="small"
              type="success">添加好友</van-button>
          </view>
        </view>

      </view>


      <u-empty v-if="friendList.length <= 0" text="暂无申请，快去添加好友吧~" mode="list"></u-empty>

    </view>

    <van-dialog v-model:show="show" title="添加好友" show-cancel-button :before-close="handleBeforeClose">
      <view style="padding: 40rpx;">确认添加 "{{ showContent }}" 为好友吗？</view>
    </van-dialog>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { Dialog } from 'vant';
//api
import { socialApi, userApi } from '@/api'
import RongIMLib from '@/packageD/common/rongCloud/im_init';
//工具
import { useConfigStore, useChatStore, useUserStore } from '@/store'
import { getImgFullPath } from "@/utils";
import { route } from '@/utils/common';

//#region  **************************** 定义变量 ****************************/
const userStore = useUserStore()
const ryStore = useChatStore()
const groupList = ref<any>([])
const friendList = ref<any>([])
const listType = ref()
const show = ref(false);
const showContent = ref('')
const messageForm = ref({
  id: '',
  status: 1,
})  //弹窗内容
//#endregion





///#region  **************************** 处理初始数据 ****************************/

onLoad((option) => {
  listType.value = option
  console.log(option, listType.value, 22);
  if (listType.value.type == 'friend') {
    getAddFriendList()
  } else {
    getGroupList()
  }
})

onShow(() => {
  initRongCloud()
  getRongCloudToken()
})

//获取好友申请列表
const getAddFriendList = async () => {
  const { data, code } = await socialApi.circleUserApplyList()
  if (code == 200) {
    console.log(data, '2222');
    friendList.value = data
  }
}

//添加好友
const handleAddFriend = (item: any) => {
  show.value = true
  console.log(item, 'item');
  messageForm.value.id = item.id
  showContent.value = item.userDetail.name
}

// 修复后的 before-close 处理函数
const handleBeforeClose = (action: string, done: (confirm: boolean) => void) => {
  console.log(action, 77);
  new Promise((resolve) => {
    if (action === 'confirm') {
      setTimeout(async () => {
        const res = await socialApi.circleUserApplyInfo(messageForm.value)
        console.log(res, '提交成功',);
        if (res.code == 200) {
          show.value = false;
          uni.showToast({
            title: '已发送',
            icon: 'success',
          })

          getAddFriendList()
        } else {
          Dialog.alert({
            title: '提示',
            message: res.msg,
          }).then(() => {
            show.value = true;
          });
        }
        resolve(true);
      }, 1000);
    } else {
      // 拦截取消操作
      show.value = false;
      resolve(false);
    }

  });
};

/**
 * ************************************ 群组 *************************************
 */
//获取用户已加入的群组
const getGroupList = async () => {
  const { data, code } = await socialApi.getUserChatGroup({
    noPaging: true,
    userId: userStore?.userInfo?.id,
  })
  if (code == 200) {
    console.log(data, '2222');
    groupList.value = data
  }
}

//跳转到群聊详情
function toChat(item: {
  type?: any
  chatGroupId?: any
  id?: any
  targetId?: any,
  name?: any,
  portraitUri?: string,
  conversationType: RongIMLib.ConversationType.GROUP
}) {

  console.log('群聊===》', RongIMLib.ConversationType.GROUP, item);
  route({
    url: '/packageD/pages/chat/index',
    params: {
      targetId: item.id || item.targetId,
      userId: item.targetId,
      name: item.name,
      cid: item.id,
      type: item.type,
      conversationType: item.conversationType || RongIMLib.ConversationType.GROUP
    }
  })
}


//融云链接
const initRongCloud = () => {
  const { Events } = RongIMLib
  RongIMLib.addEventListener(Events.CONNECTING, () => {
    console.log('正在链接服务器')
  })
  RongIMLib.addEventListener(Events.CONNECTED, () => {
    console.log('已经链接到服务器')
    const includeMuted = false
    const conversationTypes = [
      RongIMLib.ConversationType.PRIVATE,
      RongIMLib.ConversationType.GROUP
    ]
    RongIMLib.getTotalUnreadCount(includeMuted, conversationTypes)
      .then((res) => {
        if (res.code === 0) {
          console.log('未读消息', res.data)
        } else {
          console.log(res.code, res.msg)
        }
      })
      .catch((error) => {
        console.log(error)
      })
    RongIMLib.addEventListener(Events.MESSAGES, (evt) => {
      const { messages } = evt
      console.log('listener==>', evt)
      if (messages && messages.length > 0) {
        messages.forEach((message) => {
          ryStore.setMessage(message, 'add')
        })
      }
    })
    RongIMLib.addEventListener(Events.EXPANSION, (evt) => {
      console.log('扩展信息：', evt)
      const { updatedExpansion, deletedExpansion } = evt;
      console.log('拓展信息更新：', updatedExpansion);
      console.log('拓展信息删除：', deletedExpansion);
    })
    RongIMLib.addEventListener(Events.CONVERSATION, (evt) => {
      console.log('会话监听：', evt);
      ryStore.updateConversation(evt)
    })
  })
}
// 获取用户融云token并建立链接
const getRongCloudToken = async () => {
  uni.showLoading({
    title: '加载中',
    mask: true
  })
  const { code, data } = await userApi.getRongCloudToken(userStore.userInfo?.id).finally(() => {
    uni.hideLoading()
  })
  if (code === 200) {
    const res = await ryStore.connect(data)
    if (res) {
      ryStore.updateMyUserProfile({
        name: userStore.userInfo?.nickname,
        portraitUri: getImgFullPath(userStore.userInfo?.avatar)?.replace(/^https:\/\/|^http:\/\//, "//")
      })
    }
  }
}




///#endregion




</script>

<style lang="scss" scoped>
.content {
  height: 100vh;
  /* 设置为视口高度 */
  overflow: hidden;
  /* 隐藏溢出内容 */
}

.title {
  margin: 20rpx 0;
  padding: 0 10px;
}

// .group-item {
//     display: flex;
//     align-items: center;

//     .group-item-left {
//         margin-right: 20rpx;
//     }
// }


//群聊天
.group {
  // margin-top: 20rpx;
  // margin-bottom: 150rpx;
  width: 100%;
  height: 100vh;
  /* 修改高度 */
  // height:  50vh;
  padding: 10rpx 20rpx;
  background-color: #fff;

  .group-item {
    width: 500rpx;
    display: flex;
    align-items: center;
    width: 100%;
    margin: 20rpx 0rpx;
  }


  .titleGicon {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 90%;
    // line-height: 80rpx;
    height: 80rpx;
    border-bottom: 3rpx solid #f2f2f2;
    margin-left: 20rpx;
    // background-color: pink;

    .word1 {
      font-size: 28rpx;
    }

    .word2 {
      // width: 80%;
      font-size: 24rpx;
      color: #b3b3b3;
    }
  }
}
</style>
